package com.project.service.Imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.bean.StudentBean;
import com.project.mapper.IRoomMapper;
import com.project.mapper.IStudentMapper;
import com.project.service.IStudentService;
import org.apache.ibatis.session.SqlSession;

public class StudentService extends BaseService implements IStudentService {
    @Override
    public void checkIn(StudentBean studentBean) {
        SqlSession session = this.getSession();
        IStudentMapper mapper = session.getMapper(IStudentMapper.class);
        mapper.checkIn(studentBean);
        session.commit();
        session.close();
    }

    @Override
    public void checkOut(Integer studentId) {
        SqlSession session = this.getSession();
        IStudentMapper mapper = session.getMapper(IStudentMapper.class);
        mapper.checkOut(studentId);
        session.commit();
        session.close();
    }

    @Override
    public void changeRoom(Integer studentId, Integer newRoomId) {
        SqlSession session = this.getSession();
        IStudentMapper mapper = session.getMapper(IStudentMapper.class);
        IRoomMapper roomMapper = session.getMapper(IRoomMapper.class);
        if (roomMapper.countMan(newRoomId)<roomMapper.findByRoomID(newRoomId)){
            mapper.changeRoom(studentId,newRoomId);
            session.commit();
            session.close();
        }else {
            session.close();
        }



    }

    @Override
    public StudentBean findById(Integer studentId) {
        SqlSession session = this.getSession();
        IStudentMapper mapper = session.getMapper(IStudentMapper.class);
        StudentBean byId = mapper.findById(studentId);
        session.close();
        return byId;
    }

    @Override
    public PageInfo<StudentBean> findStudents(String name, String className, String roomName, Integer pageNum) {
        PageHelper.startPage(pageNum, 2);
        SqlSession session = this.getSession();
        IStudentMapper mapper = session.getMapper(IStudentMapper.class);
        PageInfo<StudentBean> of = PageInfo.of(mapper.findStudents(name, className, roomName, pageNum));
        session.close();
        return of;
    }
}
